//index.js
//获取应用实例
const app = getApp()
let api = require('../../utils/interface.js');
//储存移动的位置
let touchMove = []
import Time from "../../utils/time"

let Player = require("../../utils/player"),
    audioList = [],
    player = new Player(),
    playerCurrent = {},
     videoContext = {}
Page({
    data: {
        pageIndex: 0,
        pageSize: 5,
        detailIndex: 1,
        headerPuch: [], //首页显示圈子
        animate: {
            touchMove: [],
            //是否滑动
            touchMoveFlag: [false, false, false]
        },
        isShuaXing: true,
        player: "",
        userInfo: {},
        logs: [],
        detail_list: [],
        isload: false,
        //    效果控制
        control: {
            audio: {
                id: "",
                isPlayer: true,
                isPause: false,
                startDate: '00:00',
                progress: "",
                activeProgress: {},
                aniProgress: {},
                initActProgress:{},
                initAniProgress:{},
                loadSucc: false
            },
            player: " ",
            movie: {}
        },
        //  是否获取用户信息
        isUserInfo: false,
        poster: 'http://pic.pimg.tw/pam86591/1408719752-3322564110_n.jpg',
        name: '',
        author: '',
    },
    //事件处理函数
    bindViewTap: function () {
    },
    // 滑动事件
    handletouchmove: function (e) {
        touchMove.push(e.changedTouches[0])
    },
    bindtouchend: function (e) {
        let type = e.currentTarget.dataset.bind
        if (touchMove == [] || touchMove == null || touchMove[0] == undefined) {
            touchMove = []
            return false
        }
        console.log(touchMove)
        let moveY = touchMove[touchMove.length - 1].pageY - touchMove[0].pageY
        let moveX = touchMove[touchMove.length - 1].pageX - touchMove[0].pageX
        if (moveX > 150) {
            console.log("test")
            return false
        }
        console.log(moveY)
        // if (moveY > -20) {
        //   this.touchMove(type)
        // } else if (moveY > 10) {
        //   this.touchMove(type)
        // }
        if (moveY > -20 && moveY < 20) {
            if (moveX < -35 || moveX > 35) {
                this.touchMove(type)
            }
        }
        touchMove = []
        return false
    },
    // 首页滑动事件
    touchMove: function (type) {
        const animate = this.data.animate,
            moveTouch = wx.createAnimation({
                duration: 500,
            });
        if (!animate.touchMoveFlag[type]) {
            moveTouch.translate(-80).step()
            animate.touchMoveFlag[type] = true
        } else {
            moveTouch.translate(0).step()
            animate.touchMoveFlag[type] = false
        }
        animate.touchMove[type] = moveTouch.export();
        this.setData({
            animate: animate
        })
    },
    // 初始化录音
    initAudio: function () {
        const that = this,
            logs = that.data.logs;
         player.list.clear()
        let audioData = []
        console.log(logs)
        console.log(player.list)
        audioList = []
        for (let i = 0; i < logs.length; i++) {
            if (logs[i].ContentRadio != "") {
                audioList.push({
                    id: "aa",
                    dataUrl: logs[i].ContentRadio,
                    title: i,
                    index: i,
                })
            }
        }
        console.log(audioList)
        player.list.create(audioList)
        console.log(player.list.info())

    },
    //    录音播放实例
    createAudioPlay: function (e) {
        const that = this,
            control = that.data.control,
            time = new Time(),
            isPlayer = control.audio.isPlayer,
            url = e.currentTarget.dataset.bind
        let index;
        for (let j = 0; j < audioList.length; j++) {
            if (audioList[j].index == url) {
                console.log(audioList[j])
                index = audioList[j]._id
            }
        }
        control.audio.id = url
        console.log(index)
        player.list.syncIndex(audioList[index])

        console.log("别的")
        //      判断是否点击当前录音
            if (player.list.current() != null && playerCurrent.index != url) {
                player.stop()
                if (!player.isStopped()){
                    player.stop()
                }
                wx.stopBackgroundAudio()
                player.stop()
                //    初始化进度条    点击别的录音
                that.audioProgressAnimation(0, control.audio.progress, "00:00")
                // 全部停止

                console.log("开始播放别的-----------")
                setTimeout(function () {
                    player.invoke(index)
                }, 100)
                control.audio.isPlayer = false
                that.setData({
                    control: control
                })

                player.event.on('timeupdate', function (data) {
                    console.log("开始监听")
                    if (data.status == 1) {
                        console.log("adasdasdasdsa")
                        let duration = data.duration,
                        currentPosition = data.currentPosition
                        let startDate = time.secondConvertMinute(Math.floor(currentPosition))
                        console.log('----时长--------播放时长------------')
                        console.log('----'+Math.ceil(currentPosition)+'----------'+duration)
                        let actWidth = parseFloat(currentPosition / duration)
                        that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                        console.log(data)
                        if (Math.ceil(duration) == Math.ceil(currentPosition)) {
                            player.stop()
                            control.audio.isPlayer = true
                            that.setData({
                                control: control
                            })
                            that.audioProgressAnimation(0, control.audio.progress, "00:00")
                        } else {
                            //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                        }
                    }
                })
            }
            else {
                console.log("点击自己")
                player.event.on('timeupdate', function (data) {
                    console.log("开始监听")
                    if (data.status == 1) {
                        console.log("adasdasdasdsa")
                        let duration = data.duration,
                            currentPosition = data.currentPosition
                        let startDate = time.secondConvertMinute(Math.floor(currentPosition))
                        console.log('----时长--------播放时长------------')
                        console.log('----'+Math.ceil(currentPosition)+'----------'+duration)
                        let actWidth = parseFloat(currentPosition / duration)
                        that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                        console.log(data)
                        if (Math.ceil(duration) == Math.ceil(currentPosition)) {
                            player.stop()
                            control.audio.isPlayer = true
                            that.setData({
                                control: control
                            })
                            that.audioProgressAnimation(0, control.audio.progress, "00:00")
                        } else {
                            //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                        }
                    }
                })

                //点击当当前的录音
                console.log("ahhh")
                // 是否播放
                if (isPlayer) {
                    console.log("创建播放")
                    if (player.isPaused()) {
                        console.log("继续播放")
                        player.resume()
                    }
                    else {
                        if (!player.isPlaying()) {
                            console.log("开始播放")
                            player.invoke(index)
                        }
                    }
                    console.log(player.list.current())
                    control.audio.isPlayer = !isPlayer
                    that.setData({
                        control: control
                    })

                } else {
                    if (!player.isPaused()) {
                        player.pause()
                    }
                    control.audio.isPlayer = !isPlayer
                    that.setData({
                        control: control
                    })

                }
            }
        playerCurrent = player.list.current()
        console.log(player.list.current())
    },
    //    录音播放进度条
    AudioProgress: function () {
        const that = this,
            control = that.data.control;
        let systemInfo = {}
        wx.getSystemInfo({
            success: res => {
                systemInfo = res
            }
        })
        control.audio.progress = systemInfo.screenWidth * 0.3
        this.setData({
            control: control
        })
    },
    //    录音播放进度条动画
    audioProgressAnimation: function (activeProgress, progresWidth, startDate) {
        const that = this,
            control = that.data.control,
            activePro = wx.createAnimation({}),
            aniPro = wx.createAnimation({}),
            initact = wx.createAnimation({}),
            initani =  wx.createAnimation({})
        //  根据歌曲播放百分比 获取active长度
        const width = progresWidth * activeProgress
        let actWidth = parseFloat(progresWidth - width)
        activePro.width(width * 2).step()
        aniPro.width(actWidth).step()
        initact.width(0).step()
        initani.width(progresWidth).step()

        control.audio.activeProgress = activePro.export()
        control.audio.aniProgress = aniPro.export()
        control.audio.startDate = startDate
        control.audio.initActProgress = initact.export()
        control.audio.initAniProgress = initani.export()
        that.setData({
            control: control
        });
    },
    // 跳转到我的个人页面
    grzy: function (e) {
        wx.navigateTo({
            url: '../grzy/grzy?id=' + e.currentTarget.dataset.accid
        })
        // wx.navigateTo({
        //   url: '../fenxiang/fenxiang?id=' + e.currentTarget.dataset.accid
        // })
    },
    // 判断是否打卡或者加入
    punchCard: function (e) {
        var that = this;
        if (e.currentTarget.dataset.isfocus && !e.currentTarget.dataset.iscard) {
            wx.navigateTo({
                url: '../clockIn/clockIn?id=' + e.currentTarget.dataset.id
            });
        } else {
            wx.showLoading();
            app.Post(api.wxapp.clock_group_join, {
                groupId: e.currentTarget.dataset.id
            }, function (res) {
                wx.hideLoading();
                if (res.code == 1) {
                    app.ShowMsg("加入成功");
                    that.setData({
                        page: 1,
                        headerPuch: []
                    });
                    that.get_clock_group_list();
                } else {
                    app.WxAlert(res.msg);
                }
            });
        }
    },
    // 跳转到评论页面
    discuss: function (e) {

        console.log(e);
        wx.navigateTo({
            url: '../discuss/discuss?id=' + e.currentTarget.dataset.id + "&accid=" + e.currentTarget.dataset.accid
        });
    },
    onLoad: function () {
        console.log(app.globalData.userInfo);
        var that = this;
        that.setData({
            userInfo: app.globalData.userInfo
        });

        //this.isShowZhe()

        //this.initAudio();
        // that.get_clock_group_list();
        // that.get_clock_detail_list();

        // 页面初始化 options为页面跳转所带来的参数
        /**
         * 监听音乐播放
         */
        // wx.onBackgroundAudioPlay(function() {
        //   // callback
        //   console.log('onBackgroundAudioPlay')
        // })
        // /**
        //  * 监听音乐暂停
        //  */
        // wx.onBackgroundAudioPause(function() {
        //   // callback
        //   console.log('onBackgroundAudioPause')
        // })
        // /**
        //  * 监听音乐停止
        //  */
        // wx.onBackgroundAudioStop(function() {
        //   // callback
        //   console.log('onBackgroundAudioStop')
        // })

    },
    getUserInfo: function (e) {
        app.get_user_info(e);
    },
    // 是否关注打卡
    bindpunchcard: function (e) {
        console.log(e);
        wx.navigateTo({
            url: '../punchCard/punchCard?id=' + e.currentTarget.dataset.id
        });
    },
    // 保存用户信息
    userInfo: function (e) {
        console.log(e)
        app.get_user_info(e);
        this.setData({
            isUserInfo: true
        })
        this.initUserInfo()
    },
    // 是否显示遮罩层
    isShowZhe: function () {
        let that = this,
            isUserInfo = that.data.isUserInfo;
        if (wx.getStorageSync("userInfo")) {
            isUserInfo = true
        } else {
            isUserInfo = false
        }
        this.setData({
            isUserInfo: isUserInfo
        })
    },
    // 初始化用户信息
    initUserInfo() {
        this.setData({
            userInfo: app.globalData.userInfo
        });
        // let that = this,
        //   isUserInfo = that.data.isUserInfo,
        //   userInfo = wx.getStorageSync('userInfo');
        // console.log(userInfo)
        // if (isUserInfo) {

        // } else {
        //   return false
        // }
    },
    //    用户点击退出
    cancel: function (e) {
        var that = this;
        console.log(e);
        app.Post(api.wxapp.clock_group_quit, {
            groupId: e.currentTarget.dataset.id
        }, function (res) {
            if (res.code == 1) {
                app.ShowMsg("退出成功");
                that.setData({
                    page: 1,
                    headerPuch: []
                });
                that.get_clock_group_list();
            } else {
                app.WxAlert(res.msg);
            }
        });
    },
    //点击关注
    touchguanZhu: function (e) {
        console.log(e);
        let that = this,
            bind = e.currentTarget.dataset.bind,
            isthumbe = e.currentTarget.dataset.isthumbe,
            accountid = e.currentTarget.dataset.accountid;
        var logs = [];
        wx.showLoading()
        //添加关注
        if (!isthumbe) {
            app.Post(api.wxapp.follow_add, {
                accountId: accountid
            }, function (res) {
                wx.hideLoading();
                if (res.code == 1) {
                    for (var i = 0; i < that.data.logs.length; i++) {
                        if (accountid == that.data.logs[i].AccountId) {
                            that.data.logs[i].IsFollowd = true;
                        }
                        logs.push(that.data.logs[i]);
                    }
                    that.setData({
                        logs: logs
                    });
                    app.ShowMsg("关注成功");
                } else {
                    app.WxAlert(res.msg);
                }
            });
        } else {
            //取消关注
            app.Post(api.wxapp.follow_delete, {
                accountId: accountid
            }, function (res) {
                wx.hideLoading();
                if (res.code == 1) {
                    for (var i = 0; i < that.data.logs.length; i++) {
                        if (accountid == that.data.logs[i].AccountId) {
                            that.data.logs[i].IsFollowd = false;
                        }
                        logs.push(that.data.logs[i]);
                    }
                    that.setData({
                        logs: logs
                    });

                    app.ShowMsg("取消成功");
                } else {
                    app.WxAlert(res.msg);
                }
            });
        }


        // //赋值
        // if (!isthumbe) {
        //   that.data.logs[bind].IsFollowd = true
        // } else {
        //   that.data.logs[bind].IsFollowd = false
        // }
        // this.setData({
        //   logs: that.data.logs
        // });
    },

    // 点赞
    bindpraise: function (e) {
        let that = this,
            log = that.data.logs,
            bind = e.currentTarget.dataset.bind,
            isHeart = log[bind].IsThumbUp,
            userINfo = that.data.userInfo;
        var param = {
            detailId: e.currentTarget.dataset.id,
            type: isHeart ? 2 : 1
        };
        wx.showLoading({});
        app.Post(api.wxapp.clock_detail_thumb, param, function (res) {
            wx.hideLoading();
            if (res.code == 1) {
                if (!isHeart) {
                    log[bind].ThumbsUpList.push({
                        AccountId: app.globalData.userInfo.Id,
                        Nickname: app.globalData.userInfo.Nickname
                    });
                    log[bind].IsThumbUp = true
                    log[bind].ThumbsUpCount = log[bind].ThumbsUpCount + 1;
                } else {
                    var thums = [];
                    log[bind].IsThumbUp = false
                    log[bind].ThumbsUpCount = log[bind].ThumbsUpCount - 1;
                    for (var i = 0; i < log[bind].ThumbsUpList.length; i++) {
                        if (log[bind].ThumbsUpList[i].AccountId != app.globalData.userInfo.Id) {
                            thums.push(log[bind].ThumbsUpList[i]);
                        }
                    }
                    log[bind].ThumbsUpList = thums;
                }
                that.setData({
                    logs: log
                });
            }
        })
    },
    //获取圈子
    get_clock_group_list: function () {
        var that = this;
        if (that.data.pageIndex <= 0) {
            that.setData({
                pageIndex: 1
            });
        }
        app.Post(api.wxapp.clock_group_list, {
            page: that.data.pageIndex,
            size: that.data.pageSize
        }, function (res) {
            if (res.code == 1) {
                that.setData({
                    headerPuch: res.data
                });
            }
        });
    },
    //获取日纪
    get_clock_detail_list: function () {
        var that = this
        if (that.data.detailIndex <= 0) {
            that.setData({
                detailIndex: 1
            });
        }
        app.Post(api.wxapp.clock_detail_list, {
            groupId: 0,
            page: that.data.detailIndex,
            size: that.data.pageSize,
            isMy: 2
        }, function (res) {
            if (res.code == 1) {
                that.setData({
                    logs: that.data.logs.concat(res.data.ClockDetailList)
                });
                that.AudioProgress();
                if(player != " "){
                    console.log(player.list.info())
                    console.log(player.list.clear())
                }

                that.initAudio();
                if (res.data.ClockDetailList.length < that.data.pageSize) {
                    that.setData({
                        isload: true
                    });
                } else {
                    that.setData({
                        detailIndex: that.data.detailIndex + 1
                    });
                }
            }
        });
    },
    onReachBottom: function () {
        if (!this.data.isload) {
            this.get_clock_detail_list();
        }
    },
    bindnv: function (e) {
        wx.navigateTo({
            url: '../punchCard/punchCard?id=' + e.currentTarget.dataset.id
        })
    },
    onShow: function () {
        if (this.data.isShuaXing != undefined && this.data.isShuaXing != true) {
            this.setData({
                isShuaXing: true
            })
            return false;
        }
        this.setData({
            detailIndex: 1,
            isload: false,
            logs: [],
            page: 1,
            headerPuch: [],
            audioList: []
        });
        this.get_clock_group_list();
        this.get_clock_detail_list();
        this.slideBack()
    },
    // 滑动回退
    slideBack:function () {
        console.log(this.data.animate)
        let animate = this.data.animate
        for(let i=0;i<animate.touchMoveFlag.length;i++){
            animate.touchMoveFlag[i] = false
        }
        animate.touchMove = []
        this.setData({
            animate:animate
        })
    },
    imgYu: function (event) {
        var src = event.currentTarget.dataset.src; //获取data-src
        var imgList = event.currentTarget.dataset.list; //获取data-list
        //图片预览
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
        this.setData({
            isShuaXing: false
        })

    },
    audioPlay: function () {
        this.setData({
            action: {
                method: 'play'
            }
        });
    },
    videlplay:function(e) {
      let index = e.currentTarget.dataset.index
      var log = this.data.logs;
      log[index].isMviePlayer=true;
       videoContext = wx.createVideoContext('myVideo' + index)
        videoContext.index = index
        videoContext.requestFullScreen({
            duration:0
            })
        console.log("full")
      this.setData({
        logs:log
      })
    },
    fullVideo:function (e) {
        let log = this.data.logs
        console.log(e)
        console.log(e.detail.fullScreen)
        if(!e.detail.fullScreen){
            videoContext.pause()
            log[videoContext.index].isMviePlayer=false;
            console.log("结束全屏  ")
            this.setData({
                logs:log
            })
        }
    },
    onShareAppMessage: function () {
        return {
            title: '测试分享',
            path: '/page/index/index'
        }
    }
})